<template>
  <div class="container">
    <el-form :model="loginForm" ref="loginForm" :rules="loginFormRules" label-width="80px">
      <el-form-item label="学号" prop="id">
        <el-input type="text" v-model.lazy="loginForm.id"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="loginForm.password"></el-input>
      </el-form-item>
      <!--  按钮-->
      <el-form-item>
        <el-button type="primary" @click="submit('loginForm')">登录</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios';
import { Message } from 'element-ui';
export default {
  name: "LoginForm",
  data() {
    return {
      loginForm: {
        id: '',
        password: ''
      },
      loginFormRules: {
        id: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { min: 1, max: 20, message: '请输入12位学号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在6到18个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submit (elementName) {
      this.$refs[elementName].validate((valid) => {
        if(valid) {
          // 提交登录表单先校验 然后调用登录接口
          this.login()
        } else {
          Message.error("请输入正确学号或密码")
        }
      })
    },
    reset() {
      this.loginForm.id = ''
      this.loginForm.password = ''
    },
    login () {
      axios.post('http://localhost:3300/login', {
        id: this.loginForm.id,
        password: this.loginForm.password
      }).then(res => {
        if (res.status === 200) {
          console.log(res);
          if(res.data.id){
            // 登录成功
            localStorage.setItem('stu_info', JSON.stringify(res.data))
            this.$router.push("books")
          } else {
            Message({
              type: "error",
              message: '登录异常请重新登录'
            })
          }
        } else {
          Message({
            type: "warn",
            message: '用户名或密码不正确，或网络错误'
          })
        }
      })
    }
  }
}
</script>

<style scoped>
</style>